﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Net;
using Sami_SMS_CRM_UI;
using Sami_SMS_CRM_Business;

namespace Sami_SMS_CRM_UI
{
    public partial class casLogin : BasePage
    {
        public string ticket;
        string CAS_Server;
        string userName;
        UserRepository repository = new UserRepository();

        protected override bool RequiredLogin()
        {
            return false;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (CurUser == null)//Neu chua login
            {
                CAS_Server = ConfigurationManager.AppSettings["SSOAdress"];//https://222.255.28.64/cas/
                string MyServer = Request.Url.AbsoluteUri;
                if (MyServer.IndexOf("?") > -1) MyServer = MyServer.Substring(0, MyServer.IndexOf("?"));
                if (Request["ticket"] == null)
                {
                    string url = CAS_Server + "login?" + "service=" + Server.UrlEncode(MyServer);
                    Response.Redirect(url);
                }
                else
                {
                    ticket = Request["ticket"].ToString();
                    String url = CAS_Server + "validate?ticket=" + ticket + "&" + "service=" + Server.UrlEncode(MyServer);
                    StreamReader HtmlStream;
                    try
                    {
                        HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(url);
                        HtmlStream = new StreamReader(myHttpWebRequest1.GetResponse().GetResponseStream());
                    }
                    catch (Exception e1)
                    {
                        Response.Write("Loi lay du lieu check ticket:" + e1.Message);
                        return;
                    }
                    String resp = HtmlStream.ReadLine();
                    if (resp == "yes" || resp == "no")
                    {
                        userName = HtmlStream.ReadLine();
                        //// Attempt to Validate User Credentials using UsersDB
                        CurUser = repository.Login(userName);
                        if (CurUser != null)
                        {
                            Session[MyServer] = null;
                            RedirectToPage(ReturnURL);
                        }
                        else
                        {
                            Response.Write("Bạn không được quyền truy nhập ứng dụng này");
                        }
                    }
                    else
                    {
                        Response.Write("Bạn không được quyền truy nhập ứng dụng này");
                    }
                }
            }
            else
            {
                RedirectToPage(DefaultURL);
            }
        }
    }
}
